<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="listQuery.jobName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-select v-model="listQuery.jobGroup" clearable @keyup.enter.native="handleFilter">
                <el-option
                  v-for="item in jobGroupOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" clearable @keyup.enter.native="handleFilter">
                <el-option
                  v-for="item in enableFlagOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="可并行执行标记" prop="concurrentFlag">
              <el-select v-model="listQuery.concurrentFlag" clearable @keyup.enter.native="handleFilter">
                <el-option
                  v-for="item in concurrentFlagOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="8">
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">
              搜索
            </el-button>
            <el-button type="info" icon="el-icon-refresh" size="small" @click="handleReset">
              重置
            </el-button>
            <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="handleCreate">
              新增
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
          <el-button size="mini" type="warning" @click="handleExecute(row)">
            执行
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" prop="jobName" sortable="custom" width="250" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.jobName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务分组" prop="jobGroup" :formatter="formatter" sortable="custom" width="200" header-align="center" align="left" />
      <el-table-column label="任务执行周期" prop="cronExp" sortable="custom" width="200" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.cronExp }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务执行对象名" prop="serviceName" sortable="custom" width="300" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.serviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" sortable="custom" width="120" header-align="center" align="center" />
      <el-table-column label="可并行执行标记" prop="concurrentFlag" :formatter="formatter" width="130" header-align="center" align="center" />
      <el-table-column label="任务描述" prop="jobDesc" width="350" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.jobDesc }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="3vh" width="600px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="150px" class="form-center">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="temp.jobName" maxlength="128" />
        </el-form-item>
        <el-form-item label="任务分组" prop="jobGroup">
          <el-select v-model="temp.jobGroup">
            <el-option
              v-for="item in jobGroupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务执行周期" prop="cronExp">
          <el-tooltip placement="top">
            <div slot="content">格式: [秒] [分] [小时] [日] [月] [周] [年]
              <br>
              0 0 12 * * ? 每天12点触发<br>
              0 15 10 ? * * 每天10点15分触发<br>
              0 15 10 * * ? 每天10点15分触发<br>
              0 15 10 * * ? * 每天10点15分触发<br>
              0 15 10 * * ? 2005 2005年每天10点15分触发<br>
              0 * 14 * * ? 每天下午的 2点到2点59分每分触发<br>
              0 0/5 14 * * ? 每天下午的 2点到2点59分(整点开始，每隔5分触发)</div>
            <el-input v-model="temp.cronExp" maxlength="128" />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="任务执行对象名" prop="serviceName">
          <el-input v-model="temp.serviceName" maxlength="128" />
        </el-form-item>
        <el-form-item label="启用标记" prop="enableFlag">
          <el-select v-model="temp.enableFlag">
            <el-option
              v-for="item in enableFlagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可并行执行标记" prop="concurrentFlag">
          <el-select v-model="temp.concurrentFlag">
            <el-option
              v-for="item in concurrentFlagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="jobDesc">
          <el-input v-model="temp.jobDesc" autosize type="textarea" :rows="3" maxlength="128" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button :loading="ajaxLoading" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createScheduleJob, updateScheduleJob, deleteScheduleJob, executeScheduleJob } from '@/api/base/scheduleJob'
import Pagination from '@/components/Pagination'
import { setOptionData, valueFormate } from '@/utils/dict'

export default {
  name: 'ScheduleJob',
  components: { Pagination },
  data() {
    return {
      enableFlagOptions: [],
      concurrentFlagOptions: [],
      jobGroupOptions: [],
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        jobName: '',
        jobGroup: '',
        enableFlag: '',
        concurrentFlag: '',
        sortField: undefined,
        sortOrder: undefined
      },
      temp: {
        id: '',
        jobName: '',
        jobGroup: '',
        cronExp: '',
        jobDesc: '',
        serviceName: '',
        enableFlag: '',
        concurrentFlag: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新定时任务信息',
        create: '创建定时任务信息'
      },
      ajaxLoading: false,
      rules: {
        jobName: [{ required: true, message: '任务名称不能为空', trigger: 'change' }],
        jobGroup: [{ required: true, message: '任务分组不能为空', trigger: 'change' }],
        cronExp: [{ required: true, message: '任务执行周期不能为空', trigger: 'change' }],
        jobDesc: [{ max: 128, message: '任务描述长度不能大于128个字符', trigger: 'change' }],
        serviceName: [{ required: true, message: '任务执行对象名不能为空', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }],
        concurrentFlag: [{ required: true, message: '可并行执行标记不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('ENABLE_FLAG', this.enableFlagOptions)
    optionsMap.set('YES_OR_NO', this.concurrentFlagOptions)
    optionsMap.set('BASE_SCHEDULE_JOB_GROUP', this.jobGroupOptions)
    setOptionData(optionsMap)

    this.getList()
  },
  methods: {
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        jobName: '',
        jobGroup: '',
        enableFlag: '',
        concurrentFlag: ''
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: null,
        jobName: '',
        jobGroup: '',
        cronExp: '',
        jobDesc: '',
        serviceName: '',
        enableFlag: '',
        concurrentFlag: '',
        crrateBy: '',
        createAt: '',
        updateBy: '',
        updateAt: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ajaxLoading = true
          createScheduleJob(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.ajaxLoading = false
            this.$message({
              message: '定时任务数据保存成功！',
              type: 'success'
            })
          }, () => {
            this.ajaxLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.ajaxLoading = true
          updateScheduleJob(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.ajaxLoading = false
            this.$message({
              message: '定时任务数据更新成功！',
              type: 'success'
            })
          }, () => {
            this.ajaxLoading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '定时任务删除后将不可恢复，确认要删除该任务[' + row.jobName + ']？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteScheduleJob(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '任务[' + row.jobName + ']删除处理成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    },
    handleExecute(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '确定需要手动运行该任务[' + row.jobName + ']？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            executeScheduleJob(row.id).then(() => {
              this.$message({
                message: '任务[' + row.jobName + ']手动运行成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    }
  }
}
</script>
